package com.huawei.esdk.tp.interceptor;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;

import com.huawei.esdk.platform.common.ThreadLocalHolder;
import com.huawei.esdk.platform.common.bean.log.InterfaceLogBean;
import com.huawei.esdk.platform.common.utils.ApplicationContextUtil;
import com.huawei.esdk.platform.common.utils.OSUtils;
import com.huawei.esdk.platform.log.itf.IInterfaceLog;
import com.huawei.esdk.tp.common.constants.InfoKeys;

public class TPSmcOutInterceptor extends AbstractPhaseInterceptor<Message>
{
    private static final Logger LOGGER = Logger
            .getLogger(TPSmcOutInterceptor.class);

    public TPSmcOutInterceptor()
    {
        super(Phase.PRE_STREAM);
    }

    public void handleMessage(Message message) throws Fault
    {
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>) message
                .get(Message.PROTOCOL_HEADERS);
        if (headers == null)
        {
            headers = new HashMap<String, List<String>>();
        }

        try
        {
            String sessionId = null;
            if (ThreadLocalHolder.get() != null)
            {
                //在调用conn的时候保证将smc session放入线程变量中
                sessionId = (String) ThreadLocalHolder.get().getEntities()
                        .get(InfoKeys.SMC_SESSION_ID.toString());
            }
            if (sessionId != null)
            {
                headers.put(
                        "Cookie",
                        Collections.singletonList("ASP.NET_SessionId="
                                + sessionId));
                message.put(Message.PROTOCOL_HEADERS, headers);
            }
        }
        catch (Exception e)
        {
            LOGGER.error("", e);
            throw new Fault(e);
        }

        String targetIP = (String)message.get(Message.ENDPOINT_ADDRESS);
        try
        {
            URI uri = new URI(targetIP);
            targetIP = uri.getHost();
        }
        catch (URISyntaxException e)
        {
            e.printStackTrace();
        }
        
        String interfaceName = "";
        List<String> soapActions = headers.get("SOAPAction");
        if (null != soapActions && !soapActions.isEmpty())
        {
            String soapAction = soapActions.get(0);
            if (!StringUtils.isEmpty(soapAction) && soapAction.lastIndexOf("/") < soapAction.length())
            {
                interfaceName = soapAction.substring(soapAction.lastIndexOf("/") + 1);
                interfaceName = interfaceName.replace("\"", "");
            }
        }
        
        String messageId = (String)message.getExchange().get(LoggingMessage.ID_KEY);
        if (null == messageId)
        {
            messageId = LoggingMessage.nextId();
            message.getExchange().put(LoggingMessage.ID_KEY, messageId);
        }
        
        if (!StringUtils.isEmpty(interfaceName) && !"keepAlive".equalsIgnoreCase(interfaceName))
        {
            InterfaceLogBean bean = new InterfaceLogBean();
            bean.setTransactionId(messageId);
            bean.setProduct("TP");
            bean.setInterfaceType("2");
            bean.setProtocolType("SOAP");
            bean.setReq(true);
            bean.setName(interfaceName);
            bean.setSourceAddr(OSUtils.getLocalIP());
            bean.setTargetAddr(targetIP);
            bean.setReqTime(new Date());
            
            IInterfaceLog logger = ApplicationContextUtil.getBean("interfaceLogger");
            logger.info(bean);
        }
    }
}
